import time
import re
from DrissionPage import Chromium
from ._email_server import EmailServer

class OutlookWeb(EmailServer):
    OUTLOOK_URL = "https://login.live.com/"
    OUTLOOK_MAIL_URL = "https://outlook.live.com/mail/0/"

    def __init__(self, browser: Chromium, email, password):
        self.browser = browser
        self.email = email
        self.password = password
        self.tab = None
        self._login()

    def _login(self):
        try:
            # 打开登录页面
            self.tab = self.browser.new_tab(self.OUTLOOK_URL)
            self.tab.wait.doc_loaded()
            
            # 输入邮箱
            email_input = self.tab.ele("xpath=//input[@type='email']", timeout=10)
            email_input.input(self.email)
            time.sleep(1)  # 等待按钮变为可点击状态
            next_button = self.tab.ele("xpath=//button[@type='submit' and @data-testid='primaryButton']", timeout=10)
            next_button.click()
            self.tab.wait.doc_loaded()
            time.sleep(2)  # 等待密码页面加载
            
            # 输入密码
            password_input = self.tab.ele("xpath=//input[@type='password']", timeout=10)
            password_input.input(self.password)
            time.sleep(1)  # 等待按钮变为可点击状态
            next_button = self.tab.ele("xpath=//button[@type='submit' and @data-testid='primaryButton']", timeout=10)
            next_button.click()
            self.tab.wait.doc_loaded()
            time.sleep(2)  # 等待登录完成
            
            # 可能需要点击"是"按钮以保持登录状态
            try:
                stay_signed_in = self.tab.ele("xpath=//button[@type='submit' and contains(@class, 'primary')]", timeout=5)
                if stay_signed_in:
                    stay_signed_in.click()
                    self.tab.wait.doc_loaded()
            except:
                pass

            # 跳转到邮箱页面
            self.tab.get(self.OUTLOOK_MAIL_URL)
            self.tab.wait.doc_loaded()
            print("[OutlookWeb] Login successful")
            return True
            
        except Exception as e:
            print(f"[OutlookWeb] Login failed: {str(e)}")
            return False

    def get_email_address(self):
        return self.email
        
    def wait_for_new_message(self, delay=5, timeout=60):
        start_time = time.time()
        while time.time() - start_time <= timeout:
            try:
                # 刷新页面以获取新邮件
                self.tab.refresh()
                self.tab.wait.doc_loaded()
                time.sleep(3)  # 等待页面完全加载
                
                # 1. 先尝试直接查找包含验证码的特定div元素（最准确的方式）
                try:
                    div_elements = self.tab.eles('xpath=//div[@style="font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',Helvetica,Arial,sans-serif; font-size:28px; font-weight:400; letter-spacing:2px; line-height:30px; text-align:left; color:#202020"]', timeout=3)
                    for div in div_elements:
                        text = div.text
                        print(f"[OutlookWeb] Found special div element: {text}")
                        if len(text) == 6 and text.isdigit():
                            print(f"[OutlookWeb] Found verification code from special div: {text}")
                            return {"content": text}
                except Exception as e:
                    print(f"[OutlookWeb] Error in special div search: {str(e)}")
                
                # 2. 通过指定的邮件元素 class 查找
                try:
                    # 通过包含验证码的元素属性查找
                    cursor_emails = self.tab.eles("xpath=//div[contains(@aria-label, 'Cursor Sign in to Cursor') and contains(@aria-label, 'Your one-time code is')]", timeout=3)
                    if cursor_emails:
                        for email in cursor_emails:
                            try:
                                label = email.attr('aria-label')
                                if label:
                                    print(f"[OutlookWeb] Found email with aria-label: {label}")
                                    match = re.search(r'\b\d{6}\b', label)
                                    if match:
                                        code = match.group()
                                        print(f"[OutlookWeb] Found verification code: {code}")
                                        return {"content": code}
                            except Exception as e:
                                print(f"[OutlookWeb] Error extracting from aria-label: {str(e)}")
                except Exception as e:
                    print(f"[OutlookWeb] Error finding by aria-label: {str(e)}")
                
                # 3. 通过邮件主题定位
                try:
                    subject_xpath = "//span[contains(@class, 'TtcXM') and text()='Sign in to Cursor']"
                    subject_elements = self.tab.eles(f"xpath={subject_xpath}", timeout=3)
                    if subject_elements:
                        # 找到主题为 "Sign in to Cursor" 的邮件
                        for subject in subject_elements:
                            try:
                                # 获取包含验证码的元素
                                parent = subject
                                for _ in range(5):  # 向上查找几层父元素
                                    if parent:
                                        parent = parent.parent
                                    else:
                                        break
                                
                                if parent:
                                    # 在父元素中查找包含验证码的内容
                                    content = parent.ele("xpath=.//span[contains(@class, 'FqgPc')]", timeout=2)
                                    if content:
                                        text = content.text
                                        print(f"[OutlookWeb] Found message content: {text}")
                                        match = re.search(r'\b\d{6}\b', text)
                                        if match:
                                            code = match.group()
                                            print(f"[OutlookWeb] Found verification code from subject search: {code}")
                                            return {"content": code}
                            except Exception as e:
                                print(f"[OutlookWeb] Error processing subject element: {str(e)}")
                except Exception as e:
                    print(f"[OutlookWeb] Error finding by subject: {str(e)}")
                
                # 4. 直接通过文本内容查找
                message_xpath = "//span[contains(@class, 'FqgPc') and contains(text(), 'Your one-time code is')]"
                messages = self.tab.eles(f"xpath={message_xpath}", timeout=3)
                
                for message in messages:
                    try:
                        text = message.text
                        print(f"[OutlookWeb] Found message: {text}")
                        
                        # 提取验证码，格式为 "Your one-time code is: XXXXXX"
                        if "Your one-time code is" in text:
                            # 通过正则表达式匹配6位数字
                            match = re.search(r'\b\d{6}\b', text)
                            if match:
                                code = match.group()
                                print(f"[OutlookWeb] Found verification code from content: {code}")
                                return {"content": code}
                    except Exception as e:
                        print(f"[OutlookWeb] Error processing message: {str(e)}")
                        continue
                
                # 5. 尝试任何含有数字代码的元素
                try:
                    # 查找邮件内容中任何可能包含6位数字验证码的元素
                    any_elements = self.tab.eles("xpath=//*[string-length(normalize-space(text())) > 0]", timeout=3)
                    for element in any_elements:
                        try:
                            text = element.text
                            if text and len(text.strip()) > 0:
                                match = re.search(r'\b\d{6}\b', text)
                                if match:
                                    code = match.group()
                                    print(f"[OutlookWeb] Found verification code from any element: {code}")
                                    return {"content": code}
                        except:
                            continue
                except Exception as e:
                    print(f"[OutlookWeb] Error in any element search: {str(e)}")
                
                print("[OutlookWeb] No verification code found, waiting...")
            except Exception as e:
                print(f"[OutlookWeb] Error while checking emails: {str(e)}")
            
            time.sleep(delay)
        
        print("[OutlookWeb] Timeout waiting for verification code")
        return None
